package cn.iocoder.yudao.module.aiposter.remote;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.aiposter.config.RemoteConfig;
import cn.iocoder.yudao.module.aiposter.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.aiposter.remote.vo.*;
import cn.iocoder.yudao.module.aiposter.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class AiClient {

    @Resource
    private RemoteConfig remoteConfig;
    @Resource
    private RestTemplate restTemplate;

    /**
     * 请求获取背景
     *
     * @param requestItem 待匹配字段
     * @return 相似匹配内容
     */
    public List<AiSynthesisResp> requestBgAi(List<AiSynthesisRqe> requestItem) {
        return mockAi(requestItem);
//        if(requestItem == null || requestItem.size() == 0){
//            return new ArrayList<>();
//        }
//        String questUrl = remoteConfig.getAiPosterUrl();
//        long startTime = System.currentTimeMillis();
//        log.info("requestImgAi :{}", requestItem.toString());
//        try {
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_JSON);
//            Map<String, Object> request = new HashedMap();
//            request.put("generateList", requestItem);
//            HttpEntity<String> entity = new HttpEntity<>(JsonUtils.toJsonString(request), headers);
//            ResponseEntity<AiResp> responseEntity = restTemplate.exchange(questUrl, HttpMethod.POST, entity,
//                    AiResp.class);
//
//            log.info("requestImgAi response,cost:{}, questUrl:{} \n entity:{} \n body:{}",
//                    System.currentTimeMillis() - startTime, questUrl, entity, responseEntity.getBody());
//
//            //TODO 可能需要图床上传
//
//            return Objects.requireNonNull(responseEntity.getBody().getData());
//        } catch (Exception e) {
//            log.error("requestImgAi error", e);
//        }
//        return null;
    }

    /**
     * 请求获取AI合成图片
     *
     * @param requestItem 待匹配字段
     * @return 相似匹配内容
     */
    public List<AiSynthesisResp> requestImgAi(AiSynthesisRqe requestItem) {
        if (requestItem == null) {
            return new ArrayList<>();
        }
        return requestImgAi(new ArrayList<AiSynthesisRqe>() {{
            add(requestItem);
        }});
    }


    /**
     * 请求获取AI合成图片
     *
     * @param requestItem 待匹配字段
     * @return 相似匹配内容
     */
    public List<AiSynthesisResp> requestImgAi(List<AiSynthesisRqe> requestItem) {
        if (requestItem == null || requestItem.size() == 0) {
            return new ArrayList<>();
        }
        String questUrl = remoteConfig.getAiPosterUrl();
        List<AiSynthesisResp> result = new ArrayList<>();
        for (AiSynthesisRqe item : requestItem) {
            long startTime = System.currentTimeMillis();
            log.info("requestImgAi :{}", item.toString());
            try {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                Map<String, Object> request = new HashedMap<>();
                if (StringUtils.isEmpty(item.getBgBase64())) {
                    String bs64 = CommonUtils.getImgBase64(item.getPageBgImg());
                    item.setBgBase64(bs64 == null ? "" : bs64);
                }
                if (StringUtils.isEmpty(item.getImgBase64())) {
                    String bs64 = CommonUtils.getImgBase64(item.getImgUrl());
                    item.setImgBase64(bs64 == null ? "" : bs64);
                }
                request.put("app_id", "cw_poster_plus");
                if (StringUtils.isNotEmpty(item.getBizName())) {
                    request.put("industry", item.getBizName());
                }
                if (StringUtils.isNotEmpty(item.getKeyword())) {
                    request.put("tags", item.getKeyword().split("[,，]"));
                }
                request.put("prompt", item.getPrompt());
                request.put("neg_prompt", item.getNegativePrompt());
                request.put("img_number", item.getImgNumber());
                request.put("bg_b64", item.getBgBase64());
                request.put("fg_b64", item.getImgBase64());
                request.put("img_size", new Integer[]{item.getPageWidth(), item.getPageHeight()});  // [宽度，高度]
                request.put("img_position", new Integer[]{item.getLeft().intValue(), item.getTop().intValue(), item.getHeight().intValue(), item.getWidth().intValue()}); // [left, top, height, width]
                request.put("ip_stop", item.getStopAt());
                request.put("ip_weight", item.getWeight());
                request.put("guidance_scale", item.getGuidanceScale());
                String requestJson = JsonUtils.toJsonString(request);
                HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
                ResponseEntity<AiClientAiPosterResp> responseEntity = restTemplate.exchange(questUrl, HttpMethod.POST, entity,
                        AiClientAiPosterResp.class);
                log.info("requestImgAi response,cost:{}, questUrl:{} \n body:{}",
                        System.currentTimeMillis() - startTime, questUrl, responseEntity.getBody().getStatus());

                // 此处禁止增加data:image/png;base64的信息，这个是前端展示需要增加的，正常base64图片不需要这个内容
                if (responseEntity.getBody().getData().size() > 0) {
                    for (AiClientAiPosterResp.Item repItem : responseEntity.getBody().getData()) {
                        AiSynthesisResp itemResp = BeanUtils.toBean(item, AiSynthesisResp.class);
                        itemResp.setBase64(repItem.getBase64());
                        result.add(itemResp);
                    }
                } else {
                    throw new ServiceException(ErrorCodeConstants.POSTER_AI_POSTER_DATA_ERROR);
                }
            } catch (ServiceException e) {
                throw e;
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException(ErrorCodeConstants.POSTER_AI_POSTER_HTTP_ERROR);
            }
        }
        return result;
    }

    /**
     * 请求获取文本
     *
     * @param requestItem 待匹配字段
     * @return 相似匹配内容
     */
    public List<AiSynthesisResp> requestTextAi(List<AiSynthesisRqe> requestItem) {
        return mockAi(requestItem);
//        if(requestItem == null || requestItem.size() == 0){
//            return new ArrayList<>();
//        }
//        String questUrl = remoteConfig.getAiPosterUrl();
//        long startTime = System.currentTimeMillis();
//        log.info("requestImgAi :{}", requestItem.toString());
//        try {
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_JSON);
//            Map<String, Object> request = new HashedMap();
//            request.put("generateList", requestItem);
//            HttpEntity<String> entity = new HttpEntity<>(JsonUtils.toJsonString(request), headers);
//            ResponseEntity<AiResp> responseEntity = restTemplate.exchange(questUrl, HttpMethod.POST, entity,
//                    AiResp.class);
//
//            log.info("requestImgAi response,cost:{}, questUrl:{} \n entity:{} \n body:{}",
//                    System.currentTimeMillis() - startTime, questUrl, entity, responseEntity.getBody());
//            return Objects.requireNonNull(responseEntity.getBody().getData());
//        } catch (Exception e) {
//            log.error("requestImgAi error", e);
//        }
//        return null;
    }

    public List<AiSynthesisResp> requestSegmentation(List<AiSynthesisRqe> requestItem){
        return requestSegmentation(requestItem, new SegmentationParam());
    }
    /**
     * 请求抠图，获取抠图结果
     *
     * @return 扣图完成的结果元素列表
     */
    public List<AiSynthesisResp> requestSegmentation(List<AiSynthesisRqe> requestItem, SegmentationParam param) {
        if (requestItem == null || requestItem.size() == 0) {
            return new ArrayList<>();
        }
        String questUrl = remoteConfig.getAiSegmentationUrl();
        List<AiSynthesisResp> result = new ArrayList<>();
        for (AiSynthesisRqe item : requestItem) {
            long startTime = System.currentTimeMillis();
            log.info("requestSegmentation :{}", item.toString());
            try {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                Map<String, Object> request = new HashedMap<>();
                String normanBase64 = item.getImgBase64().replaceAll("[\r\n]", "");
                request.put("app_id", "cw_poster_plus");
                request.put("inputs", normanBase64);
                request.put("seg_model", param.getSegModel());
                request.put("seg_pattern", param.getSegPattern());
                request.put("return_type", param.getReturnType());
                HttpEntity<String> entity = new HttpEntity<>(JsonUtils.toJsonString(request), headers);
                ResponseEntity<AiClientSegmentationResp> responseEntity = restTemplate.exchange(questUrl, HttpMethod.POST, entity,
                        AiClientSegmentationResp.class);
                log.info("requestSegmentation response,cost:{}, questUrl:{} \n body:{}",
                        System.currentTimeMillis() - startTime, questUrl, responseEntity.getBody().getStatus());
                AiSynthesisResp itemResp = BeanUtils.toBean(item, AiSynthesisResp.class);
                // 此处禁止增加data:image/png;base64的信息，这个是前端展示需要增加的，正常base64图片不需要这个内容
                itemResp.setBase64(responseEntity.getBody().getSegImg());
                result.add(itemResp);
            } catch (Exception e) {
                log.error("requestSegmentation error", e);
            }
        }
        return result;
    }

    /**
     * 临时模拟AI生成的结果
     *
     * @param requestItem
     * @return
     */
    private List<AiSynthesisResp> mockAi(List<AiSynthesisRqe> requestItem) {
        List<AiSynthesisResp> result = new ArrayList<>();
        requestItem.forEach(item -> {
            AiSynthesisResp resp = BeanUtils.toBean(item, AiSynthesisResp.class);
            resp.setImgUrl("/mock/mock.jpeg");
            resp.setText("模拟AI");
            result.add(resp);
        });
        return result;
    }
}
